package com.iflytek.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iflytek.common.Result;
import com.iflytek.dao.PermissionDao;
import com.iflytek.dao.RoleDao;
import com.iflytek.document.PermissionDocument;
import com.iflytek.document.RoleDocument;
import com.iflytek.dto.PageDTO;
import com.iflytek.dto.PermissionDTO;
import com.iflytek.mapper.PermissionMapper;
import com.iflytek.model.Permission;
import com.iflytek.model.Role;
import com.iflytek.service.PermissionService;
import com.iflytek.service.RoleService;
import com.iflytek.utils.CopyUtil;
import com.iflytek.vo.PageVO;
import com.iflytek.vo.PermissionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 权限菜单表 服务实现类
 * </p>
 *
 * @author h_t
 * @since 2023-09-23
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private PermissionService permissionService;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionDao permissionDao;

    @Resource
    private RoleDao roleDao;

    /**
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<List<PermissionVO>> findAll() {
        List<Permission> permissionList = new ArrayList<>();
        Iterable<PermissionDocument> all = permissionDao.findAll();
        List<PermissionDocument> permissionDocuments = new ArrayList<>();
        all.forEach(s->{
            permissionDocuments.add(s);
        });
        if (!StringUtils.isEmpty(permissionDocuments)){
            permissionList = CopyUtil.copyList(permissionDocuments, Permission.class);
        }else {
            QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
            permissionList = permissionMapper.selectList(queryWrapper);
        }

        List<PermissionVO> permissionVOList = CopyUtil.copyList(permissionList, PermissionVO.class);
        return Result.success(permissionVOList);
    }

    /**
     * savePermission
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> savePermission(PermissionDTO dto) {
        //Permission permission = new Permission();
        if (dto == null) {
            return Result.error("1", "内容为空");
        }
        Permission permission = CopyUtil.copy(dto, Permission.class);
        if (StringUtils.isEmpty(permission.getId())) {
            if (StringUtils.isEmpty(permission)) {
                return Result.error("1", "保存失败");
            }

        }
        permissionMapper.insert(permission);
        permissionDao.deleteById(permission.getId());
        PermissionDocument copy = CopyUtil.copy(permission, PermissionDocument.class);
        permissionDao.save(copy);
        return Result.success(true);
    }

    /**
     * updatePermission
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> updatePermission(PermissionDTO dto) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(dto, permission);
        int count = permissionMapper.updateById(permission);

        if (count > 0) {
            PermissionDocument copy = CopyUtil.copy(permission, PermissionDocument.class);
            permissionDao.save(copy);
            return Result.success(true);
        } else {
            return Result.error("1", "更新失败");
        }
    }

    /**
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<PermissionVO> findById(Long id) {
        Permission permission;
        if (id == null) {
            Result.error("401", "id为空");
        }
        Optional<PermissionDocument> byId = permissionDao.findById(id);
        PermissionDocument document = byId.get();
        if (!StringUtils.isEmpty(document)){
            permission = CopyUtil.copy(document, Permission.class);
        }else {
            permission = permissionMapper.selectById(id);
        }

        PermissionVO permissionVO = CopyUtil.copy(permission, PermissionVO.class);

        return Result.success(permissionVO);
    }


    /**
     * @param dto
     * @return
     */
    @Override
    public Result<List<PermissionVO>> getByRoles(PermissionDTO dto) {
        List<PermissionVO> permissionVOList = new ArrayList<>();

        //拿预热的数据
        Optional<RoleDocument> roleDocument = roleDao.findById(dto.getId());
        Set<Long> permissionIdSet = new HashSet<>();
        RoleDocument document = roleDocument.get();
        if (!StringUtils.isEmpty(document)){

            Role role = CopyUtil.copy(document, Role.class);
            //查到role中的permission
            JSONArray objects1 = JSONUtil.parseArray(role.getPermission());
            objects1.forEach(pa -> {
                permissionIdSet.add(Long.parseLong(pa.toString()));
            });
            Iterable<PermissionDocument> allById = permissionDao.findAllById(permissionIdSet);
            List<PermissionVO> finalPermissionVOList = permissionVOList;
            allById.forEach(s->{
                finalPermissionVOList.add(CopyUtil.copy(s, PermissionVO.class));
            });
        }else {

            //通过roleService.listByIds()查
            Role role = roleService.getById(dto.getId());
            //查到role中的permission
            JSONArray objects1 = JSONUtil.parseArray(role.getPermission());
            objects1.forEach(pa -> {
                permissionIdSet.add(Long.parseLong(pa.toString()));
            });
            //通过permission拿的permission表中的权限
            Collection<Permission> permissions = permissionService.listByIds(permissionIdSet);
            //把permissions写进permissionVOList
            permissionVOList = new ArrayList(permissions);
        }

        return Result.success(permissionVOList);
    }

    /**
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<PermissionVO> deleteById(Long id) {

        if (id == null) {
            Result.error("401", "id为空");
        }
        int i = permissionMapper.deleteById(id);

        if (i > 0) {
            permissionDao.deleteById(id);
            Result.success();
        } else {

            Result.error("204", "错误");
        }
        return Result.success();
    }

    @Override
    public Result<PageVO<PermissionVO>> findPage(PageDTO<PermissionDTO> dto) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(dto.getName())) {
            queryWrapper.lambda().like(Permission::getName, dto.getName());
        }
        if (dto.getPageNum() == null) {
            dto.setPageNum(1);
        }
        if (dto.getSize() == null) {
            dto.setSize(5);
        }
        //分页
        PageHelper.startPage(dto.getPageNum(), dto.getSize());

        List<Permission> permissions = permissionMapper.selectList(queryWrapper);
        List<PermissionVO> permissionVOList = CopyUtil.copyList(permissions, PermissionVO.class);

        PageInfo<Permission> permissionPageInfo = new PageInfo<>(permissions);
        PageVO<PermissionVO> pageVO = new PageVO<>();
        BeanUtils.copyProperties(dto, pageVO);
        pageVO.setTotal(permissionPageInfo.getTotal());
        pageVO.setRecords(permissionVOList);
        return Result.success(pageVO);
    }



}
